<template>
	<uni-loading v-if="loading"></uni-loading>
	<view class="body" v-else>
		<!--  顶部  -->
		<top-tab :options="stockList" :locationName="locationName" @stockChange="stockChange"
			@handleBarnChoose="handleBarnChoose"></top-tab>


		<view class="top-container no-top" style="height: 130px;">
			<!-- #ifdef APP-PLUS -->
			<!-- <view class="top-container-inner top-container-fiexd" :style="{top: `60px`}"> -->
			<!-- #endif -->
			<!-- #ifndef APP-PLUS -->
			<!-- <view class="top-container-inner top-container-fiexd" :style="{top: `104px`}"> -->
			<!-- #endif -->
			<view class="top-container-inner">
				<uni-list :border="false">
					<uni-list-item :border="false" title="已扫箱数" :rightText="scannedSum ? scannedSum : '0'" />
					<uni-list-item :border="false" title="已扫重量" :rightText="Number(countSum ? countSum : '0').toFixed(2)" />
					<uni-list-item :border="false" title="已扫任务数" :rightText="taskSum ? taskSum : '0'" />
				</uni-list>
			</view>
		</view>

		<!--  列表  -->
		<template v-if="purchaseList && purchaseList.length > 0">
			<uni-swipe-action>
				<uni-swipe-action-item :disabled="header.status === 'audit'" :left-options="options"
					v-for="(item, index) in purchaseList" @click="handleDelete(index)">
					<view class="panel" @click="openDetail(item, index)">
						<view class="panel_title" :class="{error: item.error}">
							<view class="panel_title_left">{{ item.taskBillNo }}</view>
						</view>
						<view class="panel_content">
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">物料：</view>
									<view class="panel_content_row_item_value">{{ item.materialName }}</view>
								</view>
							</view>
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">批次：</view>
									<view class="panel_content_row_item_value">{{ item.batchNo }}</view>
								</view>
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">规格：</view>
									<view class="panel_content_row_item_value">{{ item.materialSpec }}</view>
								</view>
							</view>
							<view class="panel_content_row">
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">箱数：</view>
									<view class="panel_content_row_item_value">{{ item.currentCount }}</view>
								</view>
								<view class="panel_content_row_item">
									<view class="panel_content_row_item_title">重量：</view>
									<view class="panel_content_row_item_value">{{ Number(item.sumCount).toFixed(2) }}</view>
								</view>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</template>
		<uni-empty-info v-else label="暂无数据"></uni-empty-info>

		<!--  底部按钮  -->
		<view class="footerPanel">
			<view class="footerPanel_body">
				<button @click="handleConfirm" class="footerBtn save">
					<i class="iconfont icon-shengchenggongdan btn_icon"></i>提交
				</button>
				<button @click="handleScanCode" class="footerBtn scan" type="primary"><i
						class="iconfont icon-saomiao btn_icon"></i>扫码
				</button>
			</view>
		</view>

		<!-- 弹出层 -->
		<MaterialPopupThin ref="materialPopupThinRef" title="物料扫描" type="finished" @scanSuccess="handleScanSuccess"
			@success="addUserAllocationBoxList" :key="dataKey">
		</MaterialPopupThin>

		<BarnPopup ref="barnPopup" @confirm="onLocationChange"></BarnPopup>

		<!-- 详情 -->
		<Detail ref="detailRef" @delete="deleteMaterialBox"></Detail>
	</view>
</template>
<script>
	import topTab from "@/components/top-tab/top-tab"
	import uniLoading from "../../vBase/components/uni-loading/uni-loading"
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info"
	import MaterialPopupThin from "@/components/popup/materialPopupThin.vue"
	import BarnPopup from "@/components/popup/barnPopup.vue"
	import Detail from "../pop/detail-material.vue"

	export default {
		components: {
			topTab,
			uniLoading,
			uniEmptyInfo,
			MaterialPopupThin,
			BarnPopup,
			Detail
		},
		data() {
			return {
				loading: false,
				purchaseList: [],
				header: {},
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF4E74'
					}
				}],
				stockList: [],
				stockList: [],
				locationName: '',
				locationNo: '',
				stockNo: '',
				scannedSum: 0,
				countSum: 0,
				taskSum: 0,
				detailIndex: null,
				
			}
		},
		async onLoad() {
			await this.getStockList();
			this.initData()
		},
		methods: {
			
			/** 查询仓库*/
			async getStockList() {
				this.loading = true;
				try {
					let {
						res,
						stockList = []
					} = await this.$api.getCustomerStock();
					if (!res) return;
					this.stockList = stockList;
					if (stockList.length) this.stockNo = stockList[0].stockNo;
				} finally {
					this.loading = false;
				}
			},

			/** 初始化数据 */
			initData() {
				this.getDataList()
			},

			/**
			 * 查看详情
			 */
			async openDetail(material, i) {
				let param = {
					title: '成品明细',
					dataList: material.boxList ?? [],
				}
				this.detailIndex = i
				this.$refs.detailRef.open(param)
			},

			/**
			 * 删除箱子
			 */
			deleteMaterialBox(e) {
				let {
					material,
					success,
					index
				} = e
				let currentList = JSON.parse(JSON.stringify(this.purchaseList))
				// 如果删除了最后一个箱子,直接删除当前任务
				if (currentList[this.detailIndex].boxList.length === 1) {
					currentList.splice(this.detailIndex, 1);
				} else {
					currentList[this.detailIndex].boxList.splice(index, 1);
				}
				success && success();
				uni.showToast({
					title: "删除成功",
					icon: "none"
				})
				this.saveStorage(currentList)
			},

			/** 获取数据 */
			async getDataList() {
				this.purchaseList = uni.getStorageSync("to-be-submit-finished") ? JSON.parse(uni.getStorageSync(
					"to-be-submit-finished")) : []
				this.handleTotalCalculation()
			},

			/**
			 * 添加物料
			 * @param {Object} e
			 */
			async addUserAllocationBoxList(e, t = false) {
				try {
					let node = e.reduce((pre, cur) => {
						const curMaterial = {
							boxNo: cur.boxNo,
							batchNo: cur.batchNo,
							comment: cur.comment,
							count: cur.count,
							materialName: cur.materialName,
							materialNo: cur.materialNo,
							materialSpec: cur.materialSpec,
							currentCount: cur.currentCount,
							department: cur.department,
							inStock: cur.inStock,
							insertUserName: cur.insertUserName,
							isDelete: cur.isDelete,
							noPrint: cur.noPrint,
							standard: cur.standard,
							traceBack: cur.traceBack,
							unit: cur.unit,
							unitName: cur.unitName,
						}
						let index = pre.findIndex(v => v.taskBillNo === cur.taskBillNo && v.materialNo === cur
							.materialNo && v.batchNo === cur.batchNo)
						if (index > -1) {
							let materialIndex = pre[index].boxList?.findIndex(v => v.boxNo === cur.boxNo)
							if (materialIndex > -1) {
								uni.showToast({
									title: "请勿重复添加物料",
									icon: "none"
								})
								this.handleMediaPlayer('warning')
								// this.handleVibrate(2, 500)
								return
							} else {
								pre[index].boxList.push(curMaterial)
							}
						} else {
							pre.push({
								exp: cur.exp,
								produceDate: cur.produceDate,
								billNo: cur.billNo,
								batchNo: cur.batchNo,
								taskBillNo: cur.taskBillNo,
								materialName: cur.materialName,
								materialNo: cur.materialNo,
								materialSpec: cur.materialSpec,
								unit: cur.unit,
								boxList: [curMaterial]
							})
						}
						return pre
					}, this.purchaseList ?? [])
					this.saveStorage(node)
					this.$refs.materialPopupThinRef.close()
					uni.showToast({
						title: "添加成功",
						icon: "none"
					})
					// 如果是直接添加，这里会有提示音
					if (t) {
						this.handleMediaPlayer('success')
					}
				} finally {}
			},

			/**
			 * 总数计算
			 */
			handleTotalCalculation() {
				let taskList = []
				let boxList = []
				this.purchaseList.forEach(v => {
					if (!taskList.includes(v.taskBillNo)) {
						taskList.push(v.taskBillNo)
					}
					if (v.boxList && v.boxList.length) {
						v.currentCount = v.boxList.length
						v.sumCount = 0
						v.boxList.forEach(m => {
							// 保存所有箱子的重量，和是总重，length是已扫数量
							boxList.push(m.count)
							v.sumCount = Number(v.sumCount) + Number(m.count)
						})
					} else {
						v.currentCount = 0
					}
				})
				this.scannedSum = boxList.length
				this.countSum = boxList.reduce((pre, cur) => pre + Number(cur), 0)
				this.taskSum = taskList.length
			},

			/**
			 * 保存列表
			 * @param {Object} list
			 */
			saveStorage(list) {
				this.purchaseList = JSON.parse(JSON.stringify(list))
				this.handleTotalCalculation()
				uni.setStorageSync("to-be-submit-finished", JSON.stringify(this.purchaseList))
			},

			/** 提交 */
			handleConfirm() {
				let stockName = this.stockList.find(v => v.stockNo === this.stockNo).stockName
				this.$navigateTo("/pages/production/finished-products-summary", {
					stockName: stockName,
					stockNo: this.stockNo,
					locationNo: this.locationNo,
					locationName: this.locationName,
				})
			},

			/**
			 * 选择仓库
			 * @param e
			 */
			stockChange(e) {
				this.stockNo = this.stockList[e].stockNo
				this.initData()
			},

			/**
			 * 选择
			 */
			handleBarnChoose() {
				this.$refs.barnPopup.open(this.stockNo);
			},

			/** 选择仓位*/
			onLocationChange(location) {
				this.locationNo = location.locationNo;
				this.locationName = location.locationName;
			},

			/** 扫码 */
			async handleScanCode() {
				this.$refs.materialPopupThinRef.open()
			},

			/**
			 * 扫码成功
			 */
			async handleScanSuccess(e) {
				try {
					let res = await this.$api.getTaskMaterialByBox({
						boxNo: typeof e === 'string' ? [e] : e,
					})
					
					if (!res.res) return
					// 直接关闭面板
					this.materialList = res.hasOwnProperty('data') ? res.data : [res] ?? []
					if (this.materialList && this.materialList.length) {
						this.addUserAllocationBoxList(this.materialList, true)
					} else {
						uni.showToast({
							title: "未查询到物料信息",
							icon: "none"
						})
						this.handleMediaPlayer('error')
					}
				} catch (e) {
					if (e?.data?.err && "箱号已入库!" !== e?.data?.err) {
						this.handleMediaPlayer('error')
					}
				} 
			},

			/**
			 * 删除物料
			 * @param {Object} i
			 */
			handleDelete(i) {
				const self = this
				uni.showModal({
					title: '提示',
					content: '是否删除物料？',
					success(res) {
						if (res.confirm) {
							self.purchaseList.splice(i, 1)
							self.saveStorage(self.purchaseList ?? [])
							uni.showToast({
								title: '删除成功',
								icon: 'none'
							})
						}
					}
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import "../../static/css/common";

	.body {
		/* #ifdef APP-PLUS */
		height: 100vh;
		/* #endif */
		/* #ifndef APP-PLUS */
		height: calc(100vh - 44px);
		/* #endif */
	}

	.error {
		color: red;
	}

	.save {
		width: 140px !important;
	}
</style>
